package com.lh.project.common;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.annotation.TableField;
import com.lh.project.model.vo.UserVO;
import org.springframework.stereotype.Component;

import java.security.SignatureException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {
    private static String secretKey = "lh48@^732&2342";
    public static String createJWT(UserVO userVO){
        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");map.put("typ","JWT");
        //设置过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
        String token = JWT.create().withHeader(map)
                .withClaim("id", userVO.getId())
                .withClaim("nickName", userVO.getNickName())
                .withClaim("icon",userVO.getIcon())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secretKey));
        return token;
    }

    public static boolean verify(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        try {
            verifier.verify(token);
        }catch (Exception e){
            //Token过期异常
            return false;//表示验证失败，用户得重新登录
        }
        //表示验证成功
        return true;
    }

    public static UserVO getUser(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(secretKey)).build().verify(token);
        UserVO userVO = new UserVO();
        if(verify!=null){
            long id = verify.getClaim("id").asLong();
            String nickName = verify.getClaim("nickName").asString();
            String icon = verify.getClaim("icon").asString();
            userVO.setId(id);
            userVO.setIcon(icon);
            userVO.setNickName(nickName);
        }

        return userVO;
    }
}
